<template>
  <div>
    <r-search :searchForm="searchForm" :searchHandle="searchHandle" :searchData="searchData" />
    <r-table :tableHandles="tableHandles" :isSelection="false" :isPagination="true" :tableData="tableData"
      :tableCols="tableCols" :tablePage="tablePage" :isHandle="true" @refresh="init()"></r-table>
    <!-- <r-form :formRules="formRules" :formHandle="formHandle" :formData="formData" :formCols="formCols" ref="elForm"
      labelWidth="200px" dialogWidth="1000px" :isHandle="true" /> -->

    <r-form labelWidth="150px" :isHandle="true" :formRules="formRules2" :formCols="formCols2" :formHandle="formHandle2"
      :formData="formData2" ref="elForm2" :inline="false" dialogWidth="850px">
      <!-- 点击编辑按钮出现的模板，里面的站点地址 -->
      <!-- 省 -->
      <div class="zhandiandiz" v-if="isshowss"><span>省/市/区/街</span>
        <el-select v-model="sValue" placeholder="请选择省份" @change="sZhandiandizhi($event)" class="szddz">
          <el-option v-for="item in sOption" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <!-- 市 -->
        <el-select v-model="cValue" placeholder="请选择城市" @change="cZhandiandizhi($event)" class="czddz">
          <el-option v-for="item in cOption" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <!-- 区 -->
        <el-select v-model="qValue" placeholder="请选择区/县" @change="qZhandiandizhi($event)" class="qzddz">
          <el-option v-for="(item,index) in qOption" :key="index" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <!-- 街 -->
        <el-select v-model="jValue" placeholder="请选择街道" @change="jZhandiandizhi($event)" class="jzddz">
          <el-option v-for="(item,index) in jOption" :key="index" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>

      <!-- 点击编辑按钮出现的模板，里面的地图 -->
      <div slot="slot3">
        <div id="searchResultPanel" style="
            border: 1px solid #c0c0c0;
            width: 150px;
            height: auto;
            display: none;
          "></div>
        <p>
          点击地图确认坐标 经度：{{ formData2.lng }} 纬度：{{ formData2.lat }}
          <!-- *可以通过点击地图，快速找到站点地址 -->
        </p>
        <div id="l-map"></div>
      </div>
    </r-form>
    <!-- 导入查看仓门按钮的模板 -->
    <warehouse_gate :res="warehouse_gate_data" v-if="warehouse_gate_data.show"
      v-on:warehouse_gate_dall="warehouse_gate_dall"></warehouse_gate>
    <!-- 导入异常记录按钮的模板 -->
    <Abnormal_record ref="Abnormal_record"></Abnormal_record>
    <!-- 导入使用详情按钮的模板 -->
    <useDetailDialog :visible.sync="visible" :useDetail="useDetail"></useDetailDialog>
  </div>
</template>
<script>
  import baidumap from "../js/baidumap";
  import warehouse_gate from "./cus/warehouse_gate";
  import Abnormal_record from "./cus/Abnormal_record";
  import useDetailDialog from "./cus/useDetailDialog.vue";

  export default {
    components: {
      warehouse_gate,
      Abnormal_record,
      useDetailDialog,
    },
    data() {
      //编辑按钮 出现的编辑页面的行列方法
      var checkAge = (rule, value, callback) => {
        setTimeout(() => {
          if (isNaN(value)) {
            callback(new Error("请输入数字值"));
          } else {
            if (value < 0) {
              callback(new Error("不能小于0"));
            } else {
              callback();
            }
          }
        }, 200);
      };
      return {
        pt: '116.331398, 39.897445',
        isshowss: false,//控制省市区街显示隐藏
        sValue: '',   //编辑页面 站点地址 选项的值(省)
        sLabel: '',   //编辑页面 站点地址 选项的键名(省)
        sJingwei: '',   //编辑页面 站点地址 选项的经纬度(省)
        sOption: [], //编辑页面 站点地址 数据源(省)
        cValue: '',   //编辑页面 站点地址 选项的值(市)
        cLabel: '',   //编辑页面 站点地址 选项的键名(市)
        cJingwei: '',   //编辑页面 站点地址 选项的经纬度(市)
        cOption: [], //编辑页面 站点地址 数据源(市)
        qValue: '',   //编辑页面 站点地址 选项的值(区)
        qLabel: '',   //编辑页面 站点地址 选项的键名(区)
        qJingwei: '',   //编辑页面 站点地址 选项的经纬度(区)
        qOption: [], //编辑页面 站点地址 数据源(区)
        jValue: '',   //编辑页面 站点地址 选项的值(街道)
        jLabel: '',   //编辑页面 站点地址 选项的键名(街道)
        jJingwei: '',   //编辑页面 站点地址 选项的经纬度(街道)
        jOption: [], //编辑页面 站点地址 数据源(街道)
        userType: '',//反映是代理商还是运营商
        visible: false,
        useDetail: {
          deviceType: "1",
          deviceNo: "",
          deviceStatus: "",
          totalMoney: 0,
          totalOrder: 0,
          serverTime: 0,
          engaged: [],
        },

        baiduMap: null,//控制地图
        // 控制查看仓门按钮模板的显示隐藏
        warehouse_gate_data: {
          id: "",
          show: false,
        },
        searchData: {
          sn: "",
          operatorId: "",
          agentId: "",
          deviceStatus: "",
          deviceType: 1,
          siteId: '',
        },
        // 搜索框
        searchForm: [
          {
            type: "input",
            prop: "sn",
            placeholder: "设备编号",
            // width: 150
          },
          {
            type: 'select',
            prop: 'siteId',
            placeholder: '铺设站点',
            width: 150,
            options: []
          },
          {
            type: "select",
            prop: "operatorId",
            placeholder: "运营商",
            options: [],
            // width: 150,

            isShow: () => {
              return sessionStorage.role == "platform" ? true : false;
            },
          },
          {
            type: "select",
            prop: "agentId",
            placeholder: "代理商",
            options: [],
            // width: 150,
            isShow: () => {
              return sessionStorage.role == "operator" ? true : false;
            },
          },
          // 设备状态：1：（在线）运行中 2: 离线 3: 设备故障
          {
            type: "select",
            prop: "deviceStatus",
            placeholder: "设备状态",
            // width: 150,
            options: [
              {
                label: "在线",
                value: 1,
              },
              {
                label: "离线",
                value: 2,
              },
              {
                label: "故障",
                value: 3,
              },
            ],
          },
          // {
          //   type: 'input',
          //   prop: 'name',
          //   placeholder: '运维人员',
          //	 width: 150
          // },
        ],
        // 搜索按钮
        searchHandle: [
          {
            label: "搜索",
            type: "success",
            icon: "el-icon-search",
            handle: (e) => this.init(),
          },
        ],

        tableHandles: [
          // {
          //   label: "关联广告合集",
          //   type: "primary",
          //   handle: e => this.elFormVisible()
          // },
          // {
          //   label: "关联套餐",
          //   type: "primary",
          //   handle: e => this.elFormVisible()
          // },
          {
            label: "添加设备",
            type: "primary",
            handle: (e) => {
              this.formData2.id = null;
              if (this.userType == "代理商") {
                this.isshowss = true;
              }
              else {
                this.isshowss = false;
              }
              this.add();

            },
          },
          // {
          //   label: "导出数据",
          //   type: "primary",
          //   handle: e => this.elFormVisible()
          // }
        ],
        tableData: [],
        tableCols: [
          {
            label: "设备编号",
            prop: "sn",
          },
          {
            label: "二维码",
            type: "image",
            width: 100,
            prop: "qrCode",
          },
          {
            label: "设备名称",
            prop: "deviceName",
          },
          // {
          //   label: "代理商",
          //   prop: "agentName",
          // },
          {
            label: "铺设站点",
            prop: "name",//siteId
          },
          {
            label: "当前定位",
            prop: "address",
          },
          {
            label: "换电柜套餐",
            prop: "mealName",//mealId
            width: 100,
            isShow: e => this.userType == "代理商"
          },
          {
            label: "运营商",
            prop: "operatorName",
          },
          {
            label: "代理商",
            prop: "agentName",
          },
          {
            label: "运维人员",
            prop: "merName",
          },
          {
            label: "广告合集",
            prop: "advertList",
          },
          {
            label: "电量表",
            prop: "usedElectric",
          },
          {
            label: "设备状态",
            prop: "deviceStatus",
            formatter: (e) => {
              if (e.deviceStatus == 1) {
                return "(在线)运行中";
              } else if (e.deviceStatus == 2) {
                return "离线";
              } else if (e.deviceStatus == 3) {
                return "设备故障";
              } else if (e.deviceStatus == 0) {
                return "-";
              }
            },
          },
          {
            label: "更新时间",
            prop: "giftMoney",
          },
          {
            label: "启用状态",
            type: "switch",
            prop: "useStatus",
            values: [1, 2],
            change: (row) => this.changestate(row),
          },
          {
            label: "操作",
            type: "button",
            width: 250,
            btnList: [
              {
                label: "使用详情",
                type: "text",
                handle: async (row) => {
                  // console.log("row----", row);
                  const res = await this.apis.cabinet_detailList(row.id, "1");
                  this.useDetail.deviceNo = row.deviceNo;
                  this.useDetail.deviceStatus = row.deviceStatus;
                  const data = res.data.extend;
                  this.useDetail.serverTime = data.serverTime;
                  this.useDetail.totalMoney = data.totalMoney;
                  this.useDetail.totalOrder = data.totalOrder;
                  // data.engaged.map((item) => {
                  //   item.checked = false;
                  //   return item;
                  // });
                  this.useDetail.engaged = data.engaged;
                  this.visible = true;
                },
              },
              {
                label: "查看仓门",
                type: "text",
                handle: (row) => {
                  this.warehouse_gate_data.id = row.id;
                  this.warehouse_gate_data.show = true;
                },
              },
              {
                label: "异常记录",
                type: "text",
                handle: (row) => {
                  this.$refs.Abnormal_record.show_fun(row);
                },
              },
              {
                label: "使用记录",
                type: "text",
                isShow: () => {
                  const role = sessionStorage.role;
                  return role == "operator" || role == "agent" ? true : false;
                },
                handle: (row) => {
                  this.$router.push({
                    path: "/device_management-Record_of_power_exchange",
                    query: {
                      sn: row.sn,
                    },
                  });
                },
              },
              {
                label: "编辑",
                type: "text",
                handle: (row) => {
                  this.isshowss = false
                  this.add(row)
                },
              },
              {
                label: "删除",
                type: "text",
                handle: async (row) => {
                  this.$confirm("确定要删除吗?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  })
                    .then(async () => {
                      var res = await this.apis.device_del({
                        id: row.id,
                      });
                      this.$message({
                        type: "success",
                        message: "删除成功!",
                      });
                      this.init();
                    })
                    .catch(() => { });
                },
              },
            ],
          },
        ],
        tablePage: { limit: 10, page: 1, total: 0 },
        formData: {
          name: "",
          money: "",
          giftMoney: "",
          status: "",
        },
        formCols: [
          { type: "input", label: "套餐名称", width: 350, prop: "name" },
          {
            type: "input",
            label: "套餐金额",
            width: 350,
            prop: "money",
            remark: "元",
          },
          {
            type: "input",
            label: "赠送金额",
            width: 350,
            prop: "giftMoney",
            remark: "元",
          },
          { type: "switch", label: "上线/下线", width: 350, prop: "status" },
        ],
        formRules: {
          name: [{ required: true, message: "请输入套餐名称", trigger: "blur" }],
          money: [{ required: true, message: "请输入套餐金额", trigger: "blur" }],
          giftMoney: [
            { required: true, message: "请输入套餐金额", trigger: "blur" },
          ],
        },
        formHandle: [
          {
            label: "取消",
            handle: (e) => this.elFormVisible(),
          },
          {
            label: "确定",
            type: "success",
            handle: (e) => this.elFormSubmit(),
          },
        ],
        // 编辑按钮form表单的变量
        formData2: {
          deviceNo: "",
          deviceName: "",
          address: "",
          siteId: "",
          // name: '',
          id: '',
          lng: "",
          lat: "",
          operatorId: "",
          agentId: "",
          merId: "",
          // boxNum: '',
          cols: "",
          rows: "",
          sim: "",
          deviceType: "1",
          mealId: "",
          // mealName: '',

        },
        isId: false,
        // 编辑按钮form表单的数据源
        formCols2: [
          {
            type: "input",
            label: "设备编号",
            placeholder: "请输入",
            width: 350,
            prop: "deviceNo",
          },
          {
            type: "input",
            label: "设备名称",
            placeholder: "请输入",
            width: 350,
            prop: "deviceName",
          },
          // { type: 'input', label: '格子数量', placeholder: '请输入', width: 350, prop: 'boxNum' },
          {
            type: "input",
            label: "列数",
            placeholder: "请输入",
            width: 350,
            prop: "cols",
            isDisabled: (e) => (e.id ? true : false),
          },
          {
            type: "input",
            label: "行数",
            placeholder: "请输入",
            width: 350,
            prop: "rows",
            isDisabled: (e) => (e.id ? true : false),
          },
          {
            type: "input",
            label: "sim 编号",
            placeholder: "请输入",
            width: 350,
            prop: "sim",
          },
          // { type: "select", label: "设备类型", placeholder: '请输入', width: 350, prop: "deviceType",options:[
          //     {label:'换电柜',value:'1'},
          //     {label:'租车',value:'2'},
          //     {label:'充电柜',value:'3'},
          //   ] },
          {
            type: "select",
            label: "选择站点",
            placeholder: "请输入",
            width: 350,
            prop: "siteId",
            options: [],
          },
          {
            type: "select",
            label: "选择运营商",
            placeholder: "请输入",
            width: 350,
            prop: "operatorId",
            options: [],
            isShow: () => {
              return sessionStorage.role == "platform" ? true : false;
            },
          },
          {
            type: "select",
            label: "选择代理商",
            placeholder: "请输入",
            width: 350,
            prop: "agentId",
            options: [],
            // isShow: () => {
            //   return sessionStorage.role == "operator" ? true : false;
            // },
          },
          {
            type: "select",
            label: "选择运维",
            placeholder: "请输入",
            width: 350,
            prop: "merId",
            options: [],
            isShow: () => {
              return sessionStorage.role == "operator" ? true : false;
            },
          },
          {
            type: "select",
            label: "关联套餐",
            placeholder: "请输入",
            width: 350,
            prop: "mealId",
            isShow: () => {
              return this.userType == "运营商" ? false : true;
            },

          },
          { //只有新增才有，编辑没有
            type: "",
            isShow: () => {
              return !this.formData2.id && this.userType == "代理商" ? true : false;
            },
          },
          {
            type: "input",
            id: "suggestId",
            label: "站点地址",
            width: 350,
            prop: "address",
            isShow: () => {
              return this.userType == "运营商" ? false : true;
            },
          },
          {
            type: "slot", name: "slot3", label: "", prop: "lng",
            isShow: () => {
              return this.userType == "运营商" ? false : true;
            },
          },
        ],
        // 编辑按钮中的编辑页面 的输入框提示信息
        formRules2: {
          deviceNo: [{ required: true, message: "请输入", trigger: "blur" }],
          deviceName: [{ required: true, message: "请输入", trigger: "blur" }],
          // boxNum: [{ required: true, message: '请输入', trigger: 'blur' }, { validator: checkAge, trigger: 'blur' }],
          cols: [
            { required: true, message: "请输入", trigger: "blur" },
            { validator: checkAge, trigger: "blur" },
          ],
          rows: [
            { required: true, message: "请输入", trigger: "blur" },
            { validator: checkAge, trigger: "blur" },
          ],
          sim: [{ required: true, message: "请输入", trigger: "blur" }],
          // deviceType: [{ required: true, message: "请选择", trigger: "blur" }],
          siteId: [{ required: true, message: "请输入站点", trigger: "blur" }],
          mealId: [{ required: true, message: "请输入套餐", trigger: "blur" }],
          operatorId: [{ required: true, message: "请选择运营商", trigger: "blur" }],
          agentId: [{ required: true, message: "请选择代理商", trigger: "blur" }],
          merId: [{ required: true, message: "请选择运维", trigger: "blur" }],
          lng: [
            { required: true, message: "请点击地图选择经纬度", trigger: "blur" },
          ],
          address: [
            { required: true, message: "请输入详细地址", trigger: "blur" },
          ],
        },
        formHandle2: [
          {
            label: "取消",
            handle: (e) => this.elFormVisible("", "elForm2"),
          },
          {
            label: "确定",
            type: "success",
            handle: (e) => this.elFormSubmit2(),
          },
        ],
      };
    },

    computed: {},
    mounted() {
      this.init();
      this.site_list();
      //userType为1是运营商，2是代理商
      if (sessionStorage.getItem('userType') == "1") {
        this.userType = '运营商';
      }
      if (sessionStorage.getItem('userType') == "2") {
        this.userType = '代理商';
      }
      if (sessionStorage.role == "platform") {
        this.operator_list();
      }
      if (sessionStorage.role == "operator") {
        this.agent_list();
        this.maintenancer_list();
      }
      if (sessionStorage.role !== "operator") {
        this.agent_list();
      }
      this.mealExchange_list();
    },
    updated() {

      // 选择省市区街下拉框，编辑页面的站点地址会改变
      if (this.sLabel && !this.cLabel && !this.qLabel && !this.jLabel) {

        this.formData2.address = ''
        this.formData2.address = this.sLabel

      }
      else if (this.sLabel && this.cLabel && !this.qLabel && !this.jLabel) {

        this.formData2.address = ''
        this.formData2.address = this.sLabel + this.cLabel
      }
      else if (this.sLabel && this.cLabel && this.qLabel && !this.jLabel) {

        this.formData2.address = ''
        this.formData2.address = this.sLabel + this.cLabel + this.qLabel
      }
      else if (this.sLabel && this.cLabel && this.qLabel && this.jLabel) {

        this.formData2.address = ''
        this.formData2.address = this.sLabel + this.cLabel + this.qLabel + this.jLabel
      }
      else {

      }
    },
    watch: {
      // 监听省，如果下拉框的省发生改变，就会发送请求，更新市的数据
      sLabel(newV, oldV) {
        if (newV !== oldV) {
          // 调用编辑页面 --站点地址-- 城市（数据） 的方法
          this.czhandianfangfa(this.sLabel, this.sValue)
          // 当重新选择省，市区街和站点地址情况，重新更新
          this.cLabel = ''
          this.qLabel = ''
          this.jLabel = ''
          this.cValue = ''
          this.qValue = ''
          this.jValue = ''
        };
      },
      // 监听市，如果下拉框的市发生改变，就会发送请求，更新区的数据
      cLabel(newV, oldV) {
        if (newV !== oldV) {
          // 调用编辑页面 --站点地址-- 区（数据） 的方法
          this.qzhandianfangfa(this.cLabel, this.cValue)
          // 当重新选择市，区街和站点地址情况，重新更新
          this.qLabel = ''
          this.jLabel = ''
          this.qValue = ''
          this.jValue = ''
        }
      },
      // 监听区，如果下拉框的区发生改变，就会发送请求，更新街道的数据
      qLabel(newV, oldV) {
        if (newV !== oldV) {
          // 调用编辑页面 --站点地址-- 街道（数据） 的方法
          this.jzhandianfangfa(this.qLabel, this.qValue)
          // 当重新选择区，街和站点地址情况，重新更新

          this.jLabel = ''
          this.jValue = ''
        }
      },
      // 监听街道，如果下拉框的街道发生改变，就会发送请求，更新街道的数据
      // jValue(newV, oldV) {
      //   if (newV !== oldV) {
      //     console.log(newV, oldV);
      //     // 调用编辑页面 --站点地址-- 街道（数据） 的方法
      //     // this.jzhandianfangfa(this.qLabel, this.qValue)
      //   }
      // },
      lng(newV, oldV) {
        if (newV !== oldV) { console.log(newV, oldV, '==============='); }
      },

      "formData2.address": {
        handler(newVal, oldVal) {
          console.log(newVal)
          console.log(oldVal)
        },
        deep: true  // 深度监听
      },



    },

    methods: {
      // // 编辑页面 站点地址 的点击方法(省)
      sZhandiandizhi(value) {
        // console.log(value);
        let sObj = {};
        sObj = this.sOption.find((item) => {//这里的sOption就是上面遍历的数据源
          return item.value === value;//筛选出匹配数据
        });
        this.sLabel = sObj.label //拿到键名
        this.sOption.find((item) => {//经纬度
          if (item.value === value) {
            this.sJingwei = item.jingwei
          }
        });
        //拿到后端返回的经纬度，赋值给地图上的经纬度
        this.formData2.lng = this.sJingwei.split(",")[0]
        this.formData2.lat = this.sJingwei.split(",")[1]
        this.pt = this.sJingwei

      },

      // // 编辑页面 站点地址 的点击方法(市)
      cZhandiandizhi(value) {
        // console.log(value);
        let cObj = {};
        cObj = this.cOption.find((item) => {//这里的cOption就是上面遍历的数据源
          return item.value === value;//筛选出匹配数据
        });
        this.cLabel = cObj.label //拿到键名
        this.cOption.find((item) => {//经纬度
          if (item.value === value) {
            this.cJingwei = item.jingwei
          }
        });
        //拿到后端返回的经纬度，赋值给地图上的经纬度
        this.formData2.lng = this.cJingwei.split(",")[0]
        this.formData2.lat = this.cJingwei.split(",")[1]
        this.pt = this.cJingwei



      },
      // // 编辑页面 站点地址 的点击方法(区)
      qZhandiandizhi(value) {
        let qObj = {};
        qObj = this.qOption.find((item) => {//这里的cOption就是上面遍历的数据源
          return item.value === value;//筛选出匹配数据
        });
        this.qLabel = qObj.label //拿到键名
        this.qOption.find((item) => {//经纬度
          if (item.value === value) {
            this.qJingwei = item.jingwei
          }
        });
        //拿到后端返回的经纬度，赋值给地图上的经纬度
        this.formData2.lng = this.qJingwei.split(",")[0]
        this.formData2.lat = this.qJingwei.split(",")[1]
        this.pt = this.qJingwei
      },

      // // 编辑页面 站点地址 的点击方法(街道)
      jZhandiandizhi(value) {
        let jObj = {};
        jObj = this.jOption.find((item) => {//这里的jOption就是上面遍历的数据源
          return item.value === value;//筛选出匹配数据
        });
        this.jLabel = jObj.label //拿到键名
        console.log(this.jLabel);
        this.jOption.find((item) => {//经纬度
          if (item.value === value) {
            this.jJingwei = item.jingwei
          }
        });
        //拿到后端返回的经纬度，赋值给地图上的经纬度
        this.formData2.lng = this.jJingwei.split(",")[0]
        this.formData2.lat = this.jJingwei.split(",")[1]
        this.pt = this.jJingwei
      },

      // // 编辑页面地图 ---拿到城市（数据）
      czhandianfangfa(label, value) {
        this.cOption = [] //每次进来先清空城市的数据源
        this.apis.allAddressList({
          name: label,
          code: value,
        }).then((res) => {
          if (res.code === 0) {
            console.log(res);
            res.result.forEach((item) => {
              let obj = {
                label: item.name,
                value: item.adcode,
                jingwei: item.center
              }
              this.cOption.push(obj)
            })
            console.log(this.cOption);
          }
        })
      },

      // // 编辑页面地图 ---拿到区（数据）
      qzhandianfangfa(label, value) {
        this.qOption = [] //每次进来先清空区/县的数据源
        this.apis.allAddressList({
          name: label,
          code: value,
        }).then((res) => {
          if (res.code === 0) {
            res.result.forEach((item) => {
              let obj = {
                label: item.name,
                value: item.adcode,
                jingwei: item.center,
              }
              this.qOption.push(obj)
            })
          }
        })
      },
      // // 编辑页面地图 ---拿到街道（数据）
      jzhandianfangfa(label, value) {
        this.jOption = [] //每次进来先清空街道的数据源
        this.apis.allAddressList({
          name: label,
          code: value,
        }).then((res) => {
          if (res.code === 0) {
            console.log(res);
            // 增加判断，如果镇下面没有街道，就直接让街道变成空
            if (res.result.length !== 0) {
              res.result.forEach((item) => {
                let obj = {
                  label: item.name,
                  value: item.adcode,
                  jingwei: item.center,
                }
                this.jOption.push(obj)
              })
            } else {
              this.jOption = []
            }

          }
        })
      },
      async init() {
        let parm = {
          ...this.searchData,
          ...{
            pageNum: this.tablePage.page,
            pageSize: this.tablePage.limit,
          },
        };
        let res = await this.apis.device_list(parm);
        if (res) {
          let key = 'mealName'
          let keys = 'name'
          this.tableData = res.rows;
          this.tablePage.total = res.total;
          this.tableData.forEach((item) => {
            // 防止添加的属性值为空
            if (item.mealExchangeEntity) {
              item[key] = item.mealExchangeEntity.mealName
            } else {
              item[key] = '-'
            }
            // 防止添加的属性值为空
            if (item.siteEntity) {
              item[keys] = item.siteEntity.name
            } else {
              item[keys] = '-'
            }
          })

          console.log(this.tableData);

        };
        // 编辑页面 站点地址  ---拿到省份(数据)
        const addressRes = await this.apis.allAddressList({});
        if (addressRes.code === 0) {
          var array = new Array();
          addressRes.result.forEach((item) => {
            let obj = {
              label: item.name,
              value: item.adcode,
              jingwei: item.center,
            }
            this.sOption.push(obj)
            array.push(obj)
          })

          this.formCols2[this.labIndex2(this.formCols2, "address")].options = array;
        }
      },
      async elFormSubmit() {
        this.formData.state = this.formData.status == true ? 1 : 2;
        if (this.formData.id) {
          let res = await this.api.packupdate(this.formData);
          if (res) {
            this.formData.id = "";
            this.elFormVisible();
            this.init();
          }
        } else {
          let res = await this.api.packadd(this.formData);
          if (res) {
            this.elFormVisible();
            this.init();
          }
        }
      },
      async changestate(row) {
        let res = await this.apis.device_updata({
          id: row.id,
          useStatus: row.useStatus,
        });

        this.$message({
          message: "操作成功！",
          type: "success",
        });
      },

      add(row) {
        if (row) {
          this.formData2.id = row.id;
        } else {
          this.formData2.id = null;
        }
        this.elFormVisible("", "elForm2").then((res) => {
          if (this.userType == "代理商") {
            this.map().then((res) => {
              if (row) {
                Object.keys(this.formData2).forEach((key) => {
                  this.formData2[key] = row[key];
                });
              }
            });
          } else {
            if (row) {
              Object.keys(this.formData2).forEach((key) => {
                this.formData2[key] = row[key];
              });
            }
          }

        });
      },
      // 编辑按钮出现后的编辑页面的  绑定确认按钮的方法
      async elFormSubmit2() {
        this.$refs.elForm2.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            console.log(valid + '===========');
            if (this.formData2.id) {
              let res = await this.apis.device_updata(this.formData2);
              this.$message({
                type: res.code == 200 ? "success" : 'error',
                message: res.msg
              })
              if (res) {
                this.init();
                this.elFormVisible("", "elForm2");
              }
            } else {
              let res = await this.apis.device_save(this.formData2);
              this.$message({
                type: res.code == 200 ? "success" : 'error',
                message: res.msg
              })
              if (res) {
                this.init();
                this.elFormVisible("", "elForm2");
              }
            }
          }
        });
      },
      elFormDetail(row) {
        Object.keys(this.formData).forEach((key) => {
          this.formData[key] = row[key];
        });
        this.formData.status = row["state"] == 1 ? true : false;
        this.formData.id = row.id;
        // if (this.formCols[1].label == '登录密码') {
        //     this.formCols.splice(1, 1)
        // }
        this.elFormVisible();
      },
      //编辑按钮模板中的地图
      map() {
        var that = this;
        var map = baidumap(that);
        this.baiduMap = map;
        var geoc = new BMap.Geocoder();//地址解析对象
        // 点击地图 更新经纬度  
        map.addEventListener("click", function (e) {
          that.formData2.lng = e.point.lng; //点击获取地图的经纬度赋值给全局的经纬度
          that.formData2.lat = e.point.lat;
          var pt = e.point;
          // map.centerAndZoom(that.pt, 15) //设置地图中心点
          geoc.getLocation(pt, function (rs) {
            that.formData2.address = rs.address;//点击地图拿到详细地址
            var addComp = rs.addressComponents;//点击地图拿到省 市 区 街
            // that.formData.city = addComp.city;
            console.log(addComp, 332567, rs);
            // alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
          });
        });

        map.enableScrollWheelZoom(); //启用滚轮放大缩小，默认禁用
        map.enableContinuousZoom(); //启用地图惯性拖拽，默认禁用
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve();
          }, 10);
        });

      },
      //站点列表
      async site_list() {
        const res = await this.apis.site_list({
          pageNum: 1,
          pageSize: 100000,
        });

        const list = res.rows || [];
        let options = [];
        list.map((res) => {
          options.push({
            label: res.name,
            value: res.id,
          });
        });

        this.formCols2[this.labIndex2(this.formCols2, "siteId")].options =
          options;
        this.searchForm[this.labIndex2(this.searchForm, "siteId")].options =
          options;
      },

      //运营商-列表 
      async operator_list() {
        const res = await this.apis.operator_list({
          pageNum: 1,
          pageSize: 100000,
        });
        const list = res.rows || [];
        let options = [];
        list.map((res) => {
          options.push({
            label: res.name,
            value: res.id,
          });
        });

        this.formCols2[this.labIndex2(this.formCols2, "operatorId")].options =
          options;
        this.searchForm[this.labIndex2(this.searchForm, "operatorId")].options =
          options;
      },
      //代理商列表
      async agent_list() {
        const res = await this.apis.agent_list({
          pageNum: 1,
          pageSize: 100000,
        });
        if (sessionStorage.role !== "operator" && res.rows.length == 0) {
          var list = [{
            name: sessionStorage.nickName,
            id: sessionStorage.optUserId,
          }];
        } else {
          var list = res.rows || [];
        }
        let options = [];
        list.map((res) => {
          options.push({
            label: res.name,
            value: res.id,
          });
        });
        this.searchForm[this.labIndex2(this.searchForm, "agentId")].options =
          options;
        this.formCols2[this.labIndex2(this.formCols2, "agentId")].options =
          options;
      },
      //运维员列表
      async maintenancer_list() {
        const res = await this.apis.maintenancer_list({
          pageNum: 1,
          pageSize: 1000000,
        });
        const list = res.rows || [];
        let options = list.map((res) => {
          return {
            label: res.userName,
            value: res.id,
          };
        });

        this.formCols2[this.labIndex2(this.formCols2, "merId")].options = options;
      },

      //编辑页面中form表单的 关联套餐 
      async mealExchange_list() {
        const res = await this.apis.mealExchange_list({
          pageNum: 1,
          pageSize: 1000000,
        });
        const list = res.rows || [];
        let options = [];
        list.map((res) => {
          options.push({
            label: res.mealName,
            value: res.id,
          });
        });
        this.formCols2[this.labIndex2(this.formCols2, "mealId")].options =
          options;
      },
      warehouse_gate_dall() {
        this.warehouse_gate_data.show = false;
      },
    },
  };
</script>
<style scoped lang="scss">
  .el-icon-search {
    margin-right: 10px;
  }

  .Tip {
    margin-left: 20px;
  }

  #l-map {
    height: 250px;
    width: 100%;
  }

  #r-result {
    width: 100%;
  }

  .szddz {
    width: 130px;
  }

  .czddz {
    width: 130px;
  }

  .qzddz {
    width: 130px;
  }

  .jzddz {
    width: 130px;
  }

  .zhandiandiz {
    position: relative;
    top: -405px;
    left: 70px;
  }

  .zhandiandiz>span {
    margin-right: 10px;
  }

  #map {
    width: 100%;
    height: 500px;
  }

  .jingweip {
    margin-left: 80px;
    margin-bottom: 8px;
  }
</style>